﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using HRProject.Code.DAO;
using HRProject.Code.DTO;
using HRProject.Code.Common;

namespace HRProject
{
    public partial class AjaxWorktime : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            string sAction = Request.Params["action"];
            string sJobTitleId = Request.Params["jobTitleId"];
            string sYear = Request.Params["year"];
            string sMonth = Request.Params["month"];
            string sPageIndex = Request.Params["pageIndex"];

            string sAgentId = Request.Params["agentId"];
            string sDate = Request.Params["date"];

            string result = "";
            int errorCode = 0;

            try
            {
                if ("get_worktime_sheet".Equals(sAction))
                {
                    Guid jobTitleId = new Guid(sJobTitleId);
                    int year = int.Parse(sYear);
                    int month = int.Parse(sMonth);
                    int pageIndex = int.Parse(sPageIndex);

                    BLJobTitle jobTitleFilter = new BLJobTitle();
                    jobTitleFilter.Id = jobTitleId;

                    AgentDAO agentDao = new AgentDAO();
                    int totalAgents = agentDao.CountAgent(jobTitleFilter, Guid.Empty, string.Empty, Constant.DefaultMinDate, Constant.DefaultMaxDate);
                    int totalPage = Convert.ToInt32(Math.Ceiling(Convert.ToDouble(totalAgents) / Convert.ToDouble(ContentProvider.PageSize)));

                    if (pageIndex < 1)
                    {
                        pageIndex = 1;
                    }
                    if (pageIndex > totalPage)
                    {
                        pageIndex = totalPage;
                    }

                    WorktimeTableDAO worktimeDao = new WorktimeTableDAO();
                    BLWorktimeTable worktimeTable = worktimeDao.Collect(jobTitleFilter, Guid.Empty, string.Empty,
                        year, month, totalPage, ContentProvider.PageSize, pageIndex);

                    result = "[";
                    int vv = 0;
                    double fullInMonth = 28D;
                    foreach (WorktimeRow row in worktimeTable.Rows.Values)
                    {
                        double totalInMonth = 0;
                        if (vv > 0)
                        {
                            result += ",";
                        }
                        result += "{";
                        result += "\"agentId\":\"" + row.AgentId + "\"";
                        result += ",\"fullName\":\"" + row.FullName + "\"";
                        result += ",\"cell\":[";
                        int index = 0;
                        foreach (BLWorktimeRecord record in row.Cells)
                        {
                            if (index > 0)
                            {
                                result += ",";
                            }
                            result += "{";
                            result += "\"date\":\"" + year.ToString("0000") + month.ToString("00") + (index+1).ToString("00") + "\"";
                            result += ",\"isApproved\":"+record.Property.Approved;
                            result += ",\"description\":\"" + record.Property.Description +"\"";
                            string app = string.Empty;
                            switch (record.Property.Approved)
                            {
                                case 0:
                                    app = ContentProvider.GetFormat("LeaveApplicationSummary")
                                        .Replace("{0}", ContentProvider.GetFormat("NoLeaveApplication"))
                                        .Replace("{1}", ContentProvider.GetFormat("NoLeaveApplication"));
                                    break;
                                case 1:
                                    app = ContentProvider.GetFormat("LeaveApplicationSummary")
                                        .Replace("{0}", ContentProvider.GetFormat("HasLeaveApplication"))
                                        .Replace("{1}", ContentProvider.GetFormat("NoLeaveApplication"));
                                    break;
                                case 2:
                                    app = ContentProvider.GetFormat("LeaveApplicationSummary")
                                        .Replace("{0}", ContentProvider.GetFormat("NoLeaveApplication"))
                                        .Replace("{1}", ContentProvider.GetFormat("HasLeaveApplication"));
                                    break;
                                case 3:
                                    app = ContentProvider.GetFormat("LeaveApplicationSummary")
                                        .Replace("{0}", ContentProvider.GetFormat("HasLeaveApplication"))
                                        .Replace("{1}", ContentProvider.GetFormat("HasLeaveApplication"));
                                    break;
                                default:
                                    break;
                            }
                            result += ",\"leaveApplication\":\"" + app + "\"";
                            result += ",\"activities\":[";
                            int k = 0;
                            double duration = 0;
                            foreach (BLWorktime w in record.DailyActivities)
                            {
                                if (k > 0)
                                {
                                    result += ",";
                                }
                                duration += w.EndTime.Subtract(w.StartTime).TotalMinutes;
                                result += "\"" + ContentProvider.GetString("WorkFromTo")
                                    .Replace("{0}", w.StartTime.ToString("HH:mm"))
                                    .Replace("{1}", w.EndTime.ToString("HH:mm")) + "\"";
                                k++;
                            }
                            result += "]";
                            double durationRate = Convert.ToDouble(duration) / Convert.ToDouble(HRProject.Code.Common.Constant.WorkingMinutesPerDay);
                            totalInMonth += durationRate;
                            result += ",\"total\":\"" + durationRate.ToString("0.0") + "\"";
                            result += "}";
                            index++;
                        }
                        if (totalInMonth >= fullInMonth)
                        {
                            result += ",{\"total\":\"1.0\",\"isApproved\":true,\"leaveApplication\":\"\",\"activities\":[],\"bonus\":true,\"description\":\"" + ContentProvider.GetString("BonusWorktimeDay") + "\"}";
                            totalInMonth += 1.0D;
                        }
                        else
                        {
                            result += ",{\"total\":\"0.0\",\"isApproved\":true,\"leaveApplication\":\"\",\"activities\":[],\"bonus\":true,\"description\":\"\"}";
                        }
                        result += "]";
                        result += ",\"totalRow\":\""+totalInMonth.ToString("00.0")+"\"";
                        result += "}";
                        vv++;
                    }
                    result += "]";
                    result = "{\"status\":true,\"totalPage\":\""+totalPage+"\",\"pageIndex\":\""+pageIndex+"\",\"list\":" + result + "}";
                }
                else if ("get_worktime".Equals(sAction))
                {
                    Guid agentId = new Guid(sAgentId);
                    DateTime date = DateTime.ParseExact(Request.Params["date"], "yyyyMMdd", Constant.enCulture);

                    WorktimeRecordDAO worktimeRecordDao = new WorktimeRecordDAO();
                    BLWorktimeProperty propertyFilter = new BLWorktimeProperty(agentId, date);
                    BLWorktimeRecord worktimeRecord = worktimeRecordDao.Search(propertyFilter);
                    int totalHoursInMonth = worktimeRecordDao.CountTotalHoursInMonth(agentId, date.Year, date.Month);

                    result = "{";
                    result += "\"isApproved\":\"" + worktimeRecord.Property.Approved;
                    result += "\",\"description\":\"" + worktimeRecord.Property.Description + "\"";
                    string app = string.Empty;
                    switch (worktimeRecord.Property.Approved)
                    {
                        case 0:
                            app = ContentProvider.GetFormat("LeaveApplicationSummary")
                                .Replace("{0}", ContentProvider.GetFormat("NoLeaveApplication"))
                                .Replace("{1}", ContentProvider.GetFormat("NoLeaveApplication"));
                            break;
                        case 1:
                            app = ContentProvider.GetFormat("LeaveApplicationSummary")
                                .Replace("{0}", ContentProvider.GetFormat("HasLeaveApplication"))
                                .Replace("{1}", ContentProvider.GetFormat("NoLeaveApplication"));
                            break;
                        case 2:
                            app = ContentProvider.GetFormat("LeaveApplicationSummary")
                                .Replace("{0}", ContentProvider.GetFormat("NoLeaveApplication"))
                                .Replace("{1}", ContentProvider.GetFormat("HasLeaveApplication"));
                            break;
                        case 3:
                            app = ContentProvider.GetFormat("LeaveApplicationSummary")
                                .Replace("{0}", ContentProvider.GetFormat("HasLeaveApplication"))
                                .Replace("{1}", ContentProvider.GetFormat("HasLeaveApplication"));
                            break;
                        default:
                            break;
                    }
                    result += ",\"leaveApplication\":\"" + app + "\"";
                    result += ",\"activities\":[";
                    int k = 0;
                    double duration = 0;
                    foreach (BLWorktime w in worktimeRecord.DailyActivities)
                    {
                        if (k > 0)
                        {
                            result += ",";
                        }
                        duration += w.EndTime.Subtract(w.StartTime).TotalMinutes;
                        result += "\"" + ContentProvider.GetString("WorkFromTo")
                            .Replace("{0}", w.StartTime.ToString("HH:mm"))
                            .Replace("{1}", w.EndTime.ToString("HH:mm")) + "\"";
                        k++;
                    }
                    result += "]";
                    double durationRate = Convert.ToDouble(duration) / Convert.ToDouble(HRProject.Code.Common.Constant.WorkingMinutesPerDay);
                    result += ",\"total\":\"" + durationRate.ToString("0.0") + "\"";
                    result += "}";
                    string bonus = "";
                    if (totalHoursInMonth >= (Constant.WorkingMinutesPerDay/60 * 28))
                    {
                        bonus = "\"total\":\"1.0\",\"description\":\"" + ContentProvider.GetString("BonusWorktimeDay") + "\"";
                    }
                    else
                    {
                        bonus = "\"total\":\"0.0\",\"description\":\"\"";
                    }
                    result = "{\"status\":true,\"worktime\":" + result + ",\"bonus\":{"+bonus+"}}";
                }
                else if ("set_default_worktime".Equals(sAction))
                {
                    Guid jobTitleId = new Guid(sJobTitleId);
                    int year = int.Parse(sYear);
                    int month = int.Parse(sMonth);

                    errorCode = 0;
                    int updateResult = 0;
                    WorktimeDAO worktimeDao = new WorktimeDAO();
                    updateResult = worktimeDao.SetDefaultWorktime(jobTitleId, year, month, ref errorCode);
                    if (errorCode == 12)
                    {
                        result = "{\"status\":false,\"error\":\"" + ContentProvider.GetMessage("NotAuthorizedDetail").Replace("{0}", ContentProvider.GetString("Worktime")) + "\"}";
                    }
                    else
                    {
                        result = "{\"status\":true}";
                    }
                }
            }
            catch (Exception exp)
            {
                Console.Out.WriteLine(exp.Message);
            }

            Response.Clear();
            Response.ContentType = "application/json; charset=utf-8";
            Response.Write(result);
            Response.End();
        }
    }
}
